package com.chinamobile.iot.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created on 2016/12/27.
 *
 * @author stayfool
 */
public class IPUtil {

    private static final String localIp;
    private static Logger logger = LoggerFactory.getLogger(IPUtil.class);

    static {

        String wanIp = getWanIp();
        List<String> localIpList = new ArrayList<>();
        List<String> igoreIpList = Arrays.asList("0.0.0.0", "127.0.0.1");
        try {
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();

            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = allNetInterfaces.nextElement();
                String name = netInterface.getDisplayName().toLowerCase();
                if (name.contains("vmware") || name.contains("virtual"))
                    continue;
                Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress address = addresses.nextElement();
                    if (address != null && address instanceof Inet4Address
                            && !igoreIpList.contains(address.getHostAddress())) {

                        logger.info("found local ip : {}", address.getHostAddress());
                        localIpList.add(address.getHostAddress());
                    }
                }
            }
        } catch (SocketException e) {
        }

        if (wanIp != null && localIpList.contains(wanIp)) {
            localIp = wanIp;
            logger.info("this machine is on wan internet, use wan ip : {}", wanIp);
        } else if (!localIpList.isEmpty()) {
            localIp = localIpList.get(0);
            logger.info("this machine is on lan internet, use lan ip : {}", localIp);
        } else {
            localIp = "127.0.0.1";
            logger.info("this machine is out of internet use loop ip : {}", localIp);
        }
    }

    private IPUtil() {
    }

    public static String getLocalIp() {
        return localIp;
    }

    public static String getWanIp() {

        int retry = 1;
        RestTemplate rest = new RestTemplate();
        do {
            try {
                String res = rest.getForObject("http://1212.ip138.com/ic.asp", String.class);
                String ipParttern = "((?:(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d))))";
                Pattern p = Pattern.compile(ipParttern);
                Matcher m = p.matcher(res);
                if (m.find()) {
                    String ip = m.group();
                    logger.info("found wan ip : {}", ip);
                    return ip;
                }
                Thread.sleep(100);
            } catch (Exception e) {
                logger.info("find wan ip failed, retry {}", retry);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e1) {
                }
            }
        } while (retry++ < 3);

        return null;
    }
}
